package cn.itcast.service.impl;

import cn.itcast.domain.OrderSetting;
import cn.itcast.mapper.OrderSettingMapper;
import cn.itcast.service.OrderSettingService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    public void addData(List<OrderSetting> data) {
        if(data !=null && data.size()>0){
            for (OrderSetting orderSetting : data) {
                //根据date数据判断数据库中是否有记录
               long count = orderSettingMapper.findCountByDate(orderSetting.getOrderDate());
               // 如果记录有值 ,就调用修改方法
               if(count>0){
                   orderSettingMapper.editOrderSetting(orderSetting);
               }else{
                   //如果记录没有值,就调用添加方法
                   orderSettingMapper.createOrderSetting(orderSetting);
               }

            }
        }
    }

    public List<Map> getOrderSettingByMonth(String date) { //格式: yyyy-MM

        //根据日期范围查询预约设置数据
        List<OrderSetting> list = orderSettingMapper.getOrderSettingByMonth(date);
        List<Map> result = new ArrayList<Map>();
        if(list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                Map<String, Object> m = new HashMap<String,Object>();
                m.put("date", orderSetting.getOrderDate().getDate());//获取日期数字（几号）
                m.put("number", orderSetting.getNumber());
                m.put("reservations", orderSetting.getReservations());
                result.add(m);
            }
        }
        return result;
    }

    public void editNumberByDate(OrderSetting orderSetting) {
        Date orderDate = orderSetting.getOrderDate();
        String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(orderDate);
        int num = orderSetting.getNumber();
        //根据日期查询是否已经进行了预约设置
        long count = orderSettingMapper.findCountByFormatDate(formatDate);
        if(count > 0){
            //当前日期已经进行了预约设置，需要执行更新操作
            orderSettingMapper.editOrderSettings(num,formatDate);
        }else{
            //当前日期没有就那些预约设置，需要执行插入操作
            orderSettingMapper.createOrderSettings(num,formatDate,orderSetting.getReservations());
        }
    }

}
